﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Net;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.DocumentManagement.DocumentSets;
using Ko2.Portal;
using Ko2.Portal.Right;

namespace JobCreateInDocs3
{

    public static class JobCreateInDocsMethods
    {

        #region Members
        static Ko2.Portal.Env _env = new Ko2.Portal.Env();
        private static string _MachineName = "";
        private static string _ConnStr = "";
        public static string ConnStr
        {
            get
            {
                //if (_MachineName != "ws0279")
                _ConnStr = _env.GetAppSetting("AXAPTAConnect");
                return JobCreateInDocsMethods._ConnStr;
            }
        }
        static string _sUrl = "http://localhost/sites/shop/";
        static public string sUrl
        {
            get { return _sUrl; }
        }
        static string _sListName = "Первичные документы";
        static public string sListName
        {
            get { return _sListName; }
        }
        #endregion Members
        #region Constructors
        static JobCreateInDocsMethods()
        {
            _MachineName = System.Environment.MachineName.ToLower();
            _ConnStr = _env.GetAppSetting("AXAPTAConnect");
        }
        #endregion Constructors
        #region Common Methods
        public static string TRIMInvoice(String mName)
        {
            mName = mName.Replace("/", "_");
            return mName;
        }
        private static string TRIMGUID(String mName)
        {
            mName = mName.Replace("{", "");
            mName = mName.Replace("}", "");
            return mName;
        }
        private static string StringConvertName(String mName)
        {
            String tName = "";
            tName = mName.Replace("\"", "'");
            return tName;
        }
        private static OleDbConnection CreateSQLConnect()
        {
            OleDbConnection sqlConnection1 = new OleDbConnection();
            sqlConnection1.ConnectionString = ConnStr;
            sqlConnection1.Open();
            return sqlConnection1;
        }
        public static Exception GetSetting_CreateInDoc_LastSuccessfully(ref DateTime parDT)
        {
            string parStr = string.Empty;
            Exception ret = _env.GetWebSetting(ref parStr
                , "Job-CreateInDocs"
                , "LastSuccessfully"
                , "DateTime");
            if (ret != null)
                return ret;
            try
            {
                parDT = DateTime.Parse(parStr);
            }
            catch (Exception ex)
            {
                ret = new Exception(ex.Message, ex);
            }
            return ret;
        }
        public static Exception SetSetting_CreateInDoc_LastSuccessfully(DateTime parNewDT)
        {
            string parStr = parNewDT.ToString();
            Exception ret = _env.SetWebSetting(
                  "Job-CreateInDocs"
                , "LastSuccessfully"
                , "DateTime"
                , parStr);
            return ret;
        }
        public static Exception GetSetting_Shops_LastSuccessfully(ref DateTime parDT)
        {
            string parStr = string.Empty;
            Exception ret = _env.GetWebSetting(ref parStr
                , "Job-CreateShops"
                , "LastSuccessfully"
                , "DateTime");
            if (ret != null)
                return ret;
            try
            {
                parDT = DateTime.Parse(parStr);
            }
            catch (Exception ex)
            {
                ret = new Exception(ex.Message, ex);
            }
            return ret;
        }
        public static Exception SetSetting_Shops_LastSuccessfully(DateTime parNewDT)
        {
            string parStr = parNewDT.ToString();
            Exception ret = _env.SetWebSetting(
                  "Job-CreateShops"
                , "LastSuccessfully"
                , "DateTime"
                , parStr);
            return ret;
        }
        public static Exception GetSetting_Suplier_LastSuccessfully(ref DateTime parDT)
        {
            string parStr = string.Empty;
            Exception ret = _env.GetWebSetting(ref parStr
                , "Job-CreateSuplier"
                , "LastSuccessfully"
                , "DateTime");
            if (ret != null)
                return ret;
            try
            {
                parDT = DateTime.Parse(parStr);
            }
            catch (Exception ex)
            {
                ret = new Exception(ex.Message, ex);
            }
            return ret;
        }
        public static Exception SetSetting_Suplier_LastSuccessfully(DateTime parNewDT)
        {
            string parStr = parNewDT.ToString();
            Exception ret = _env.SetWebSetting(
                  "Job-CreateSuplier"
                , "LastSuccessfully"
                , "DateTime"
                , parStr);
            return ret;
        }
        #endregion Common Methods
        #region Data
        private static Exception GetDataTable(ref DataTable tbl, DateTime DateTimePoint)
        {
            Exception ret = null;
            if (tbl == null)
                tbl = new DataTable();
            ret = DBReceiptJour.GetDataByDataTime(ref tbl, DateTimePoint);
            return ret;
        }
        #endregion Data
        #region SystemSettings
        public static Exception SetLastsuccessfullyDateTime(DateTime setDT)
        {
            Exception ret = null;
            ret = SetSetting_CreateInDoc_LastSuccessfully(setDT);
            return ret;
        }
        public static Exception GetLastsuccessfullyDateTime(ref DateTime retDT)
        {
            Exception ret = null;
            if (retDT == null)
                retDT = new DateTime();
            ret = GetSetting_CreateInDoc_LastSuccessfully(ref retDT);
            return ret;
        }
        public static Exception SetLastsuccessfullyShopsDateTime(DateTime setDT)
        {
            Exception ret = null;
            ret = SetSetting_Shops_LastSuccessfully(setDT);
            return ret;
        }
        public static Exception GetLastsuccessfullyShopsDateTime(ref DateTime retDT)
        {
            Exception ret = null;
            if (retDT == null)
                retDT = new DateTime();
            ret = GetSetting_Shops_LastSuccessfully(ref retDT);
            return ret;
        }
        public static Exception SetLastsuccessfullySuplierDateTime(DateTime setDT)
        {
            Exception ret = null;
            ret = SetSetting_Suplier_LastSuccessfully(setDT);
            return ret;
        }
        public static Exception GetLastsuccessfullySuplierDateTime(ref DateTime retDT)
        {
            Exception ret = null;
            if (retDT == null)
                retDT = new DateTime();
            ret = GetSetting_Suplier_LastSuccessfully(ref retDT);
            return ret;
        }
        #endregion
        #region Doc and Lib Methods and Metadata
        #region If Exist
        public static bool inExistsDocs(String mDocName)
        {
            SPListItem item = SPListPrimaryDocs.GetItemByTitle(mDocName);
            return (item != null);
        }
        public static Exception inExistsDocs_ById(ref bool IsExist, int parId)
        {
            Exception err = null;
            SPListItem item = null;            
            err = SPListPrimaryDocs.GetItemById(ref item, parId);
            IsExist = (item != null);
            return err;
        }
        public static Exception inExistsDocs_ByAxId(ref bool IsExist, Int64 parId)
        {
            Exception err = null;
            SPListItem item = null;
            err = SPListPrimaryDocs.GetItemByAxId(ref item, parId);
            IsExist = (item != null);
            return err;
        }
        #region Metadata
        public static Term inExistsLib(String mNameLib, String mID, int lcid)
        {
            Term mRet = MetadataHelper.inExistsLib(sUrl, mNameLib, mID, lcid);
            return mRet;
            //SPSecurity.RunWithElevatedPrivileges(delegate()
            //{
            //    using (SPSite site = new SPSite(sUrl))
            //    {
            //        TaxonomySession mSess = new TaxonomySession(site);
            //        foreach (TermStore mStore in mSess.TermStores)
            //        {
            //            foreach (Group mGroup in mStore.Groups)
            //            {
            //                foreach (TermSet mSet in mGroup.TermSets)
            //                {
            //                    if (mSet.Name == mNameLib)
            //                    {
            //                        foreach (Term mTerm in mSet.Terms)
            //                        {
            //                            if (mTerm.GetDescription(lcid).Trim() == mID)
            //                            {
            //                                mRet = mTerm;
            //                            }
            //                            foreach (Term mTerm1 in mTerm.Terms)
            //                            {
            //                                if (mTerm1.GetDescription(lcid).Trim() == mID)
            //                                {
            //                                    mRet = mTerm1;
            //                                }
            //                                foreach (Term mTerm2 in mTerm1.Terms)
            //                                {
            //                                    if (mTerm2.GetDescription(lcid).Trim() == mID)
            //                                    {
            //                                        mRet = mTerm2;
            //                                    }
            //                                } // foreach (Term mTerm2 in mTerm1.Terms)
            //                            } // foreach (Term mTerm1 in mTerm.Terms)
            //                        } // foreach (Term mTerm in mSet.Terms)
            //                    } // if (mSet.Name == mNameLib)
            //                } // foreach (TermSet mSet in mGroup.TermSets)
            //            } // foreach (Group mGroup in mStore.Groups)
            //        } // foreach (TermStore mStore in mSess.TermStores)
            //    } // Site
            //});
        }
        #endregion Metadata
        #endregion If Exist
        #region Create Doc
        public static Exception Add(ref SPListItem parRet, Int64 parAxID, int parShopID, int parSuplierID, string ЗП, string Номер_накладной, DateTime Дата_наклдадной, string Магазин, string Поставщик, string uid)
        {
            Exception ret = null;
            DateTime dt = new DateTime(Дата_наклдадной.Year, Дата_наклдадной.Month, Дата_наклдадной.Day);
            //bool AllowUnsafeUpdates = false;
            using (SPSite site = new SPSite(sUrl))
            {
                using (SPWeb mWeb = site.OpenWeb())
                {
                    try
                    {
                        SPList list = mWeb.Lists[sListName];
                        parRet = list.AddItem();
                        parRet["AxID"] = parAxID;
                        parRet["ShopID"] = parShopID;
                        parRet["SuplierID"] = parSuplierID;
                        parRet["Название"] = ЗП + @"(" + Номер_накладной + @")";
                        parRet["ЗП"] = ЗП;
                        parRet["Номер накладной"] = Номер_накладной;
                        parRet["Дата наклдадной"] = dt;
                        parRet.SetFieldValueLookup("Магазин", Магазин);
                        parRet.SetFieldValueLookup("Поставщик", Поставщик);
                        parRet["uid"] = uid;
                        parRet.Update();
                        // See list events receiver
                        //if (!parRet.HasUniqueRoleAssignments)
                        //    PermDocRight.PermDocs_SetRoleItem(parRet);
                    }
                    catch (Exception err)
                    {
                        ret = new Exception(err.Message, err);
                    }
                }
            }
            return ret;
        }
        public static SPListItem InsertDocs(String mDocName, String mUser)
        {
            SPListItem mRet = null;

            using (SPSite site = new SPSite(sUrl))
            {
                using (SPWeb mWeb = site.OpenWeb())
                {
                    try
                    {
                        mWeb.AllowUnsafeUpdates = true;
                        SPList list = mWeb.Lists[sListName];
                        SPFolder folderToInsertIn = list.RootFolder;

                        SPContentTypeId dsCtId = new SPContentTypeId();
                        if (list.ContentTypes["Набор документов"] != null)
                            dsCtId = list.ContentTypes["Набор документов"].Id;
                        else
                            dsCtId = list.ContentTypes["Document Set"].Id;

                        Hashtable properties = new Hashtable();
                        //properties.Add("Номер накладной", "test");
                        //--
                        SPUser tUser = mWeb.EnsureUser(mUser);
                        DocumentSet mDoc;
                        if (tUser.LoginName != null)
                            mDoc = DocumentSet.Create(folderToInsertIn, mDocName, dsCtId, properties, true, tUser);
                        else
                            mDoc = DocumentSet.Create(folderToInsertIn, mDocName, dsCtId, properties, true);
                        //--
                        SPQuery query = new SPQuery();
                        query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + mDocName + "</Value></Eq></Where>";
                        SPListItemCollection myItems = list.GetItems(query);
                        foreach (SPListItem currentItem in myItems)
                        {
                            if (currentItem["Title"].ToString().Trim() == mDocName.Trim())
                            {
                                mRet = currentItem;
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        mRet = null;
                    }
                }
            }
            return mRet;
        }
        //private static Exception CreateInDocs(SPJobDefinition job, DateTime dt)
        //{
        //    Exception ret = null;
        //    int lcid = CultureInfo.CurrentCulture.LCID;
        //    string DomainNameStr = _env.GetAppSetting("DomainName");
        //    try
        //    {
        //        #region Get DataTable
        //        DataTable tbl = new DataTable();
        //        Exception err = DBReceiptJour.GetDataByDataTime(ref tbl, dt);
        //        #endregion Get DataTable
        //        #region Read Data

        //        foreach (DataRow row in tbl.Rows)
        //        {
        //            if (!inExistsDocs(
        //                row["WMDOCUMENTREFID"].ToString()
        //                + "("
        //                + TRIMInvoice(row["WMinvoiceId"].ToString()) + ")"))
        //            {

        //                // Insert New Item
        //                SPListItem mItem =
        //                    InsertDocs(
        //                        row["WMDOCUMENTREFID"].ToString()
        //                        + "(" + TRIMInvoice(row["WMinvoiceId"].ToString()) + ")"
        //                        , DomainNameStr + "\\" + row["NETWORKALIAS"].ToString());

        //                if (mItem != null)
        //                {
        //                    mItem["Номер накладной"] = TRIMInvoice(row["WMinvoiceId"].ToString());
        //                    mItem["Дата комплекта"] = row["WDate"].ToString();

        //                    Term mTerm;
        //                    mTerm = inExistsLib("Поставщики", row["VenderID"].ToString(), lcid);
        //                    if (mTerm != null)
        //                    {
        //                        UpdateListItemTermColumn(mItem, "Поставщик", mTerm);
        //                    }
        //                    mTerm = inExistsLib("Магазины", row["InventLocationid"].ToString(), lcid);
        //                    if (mTerm != null)
        //                    {
        //                        UpdateListItemTermColumn(mItem, "Магазин", mTerm);
        //                    }
        //                    SetRoleItem(mItem, row["Name"].ToString());
        //                    mItem.SystemUpdate();
        //                    mItem.Update();
        //                    //CreateLineLog(
        //                    //    "Add Row Doc : " + row["WMDOCUMENTREFID"].ToString()
        //                    //    + "(" + row["WMinvoiceId"].ToString() + ")"
        //                    //    , mTerm);
        //                }
        //                else // mItem != null
        //                {
        //                    Term mTerm;
        //                    mTerm = inExistsLib("Магазины", row["InventLocationid"].ToString(), lcid);
        //                    if (mTerm != null)
        //                    {
        //                        UpdateListItemTermColumn(mItem, "Магазин", mTerm);
        //                    }
        //                    //CreateLineLog("Error ADD Row Doc : "
        //                    //    + row["WMDOCUMENTREFID"].ToString() + "("
        //                    //    + row["WMinvoiceId"].ToString() + ")", mTerm);
        //                }
        //            }
        //        }

        //        #endregion Read Data
        //    }
        //    catch (Exception ex)
        //    {
        //        ret = new Exception(ex.Message, ex);
        //    }
        //    return ret;
        //}
        #endregion Create Doc
        #region Udpade
        public static void UpdateListItemTermColumn(SPListItem li, string fieldName, Term term)
        {
            SPField termField = li.Fields[fieldName];

            TaxonomyFieldValueCollection tfvc = new TaxonomyFieldValueCollection(termField);
            tfvc.Add(new TaxonomyFieldValue(termField));
            li[fieldName] = tfvc;

            TaxonomyField taxonomyField = termField as TaxonomyField;
            if (taxonomyField != null)
            {
                taxonomyField.SetFieldValue(li, term);
            }
        }
        #endregion Update
        #endregion Doc Methods
        #region Log Methods
        //public static void CreateLineLog(String mStr, Term mTerm)
        //{
        //    using (SPSite site = new SPSite(sUrl))
        //    {
        //        using (SPWeb mWeb = site.OpenWeb(sWeb))
        //        {
        //            try
        //            {
        //                SPList list = mWeb.Lists["log_InDocs"];
        //                mWeb.AllowUnsafeUpdates = true;
        //                SPListItem item = list.Items.Add();
        //                item["Title"] = "(" + DateTime.Now.ToString() + ") " + mStr;
        //                if (mTerm != null)
        //                {
        //                    UpdateListItemTermColumn(item, "Магазин", mTerm);
        //                }
        //                item.Update();
        //            }
        //            catch
        //            {
        //            }
        //        }
        //    }
        //}
        //public static void CreateLineLog1(String mStr)
        //{
        //    using (SPSite site = new SPSite(sUrl))
        //    {
        //        using (SPWeb mWeb = site.OpenWeb(sWeb))
        //        {
        //            try
        //            {
        //                SPList list = mWeb.Lists["log"];
        //                mWeb.AllowUnsafeUpdates = true;
        //                SPListItem item = list.Items.Add();
        //                item["Title"] = "(" + DateTime.Now.ToString() + ") " + mStr;
        //                item.Update();
        //            }
        //            catch
        //            {
        //            }
        //        }
        //    }
        //}
        #endregion Log Methods
        #region Rigth
        //public static void SetRoleItem(SPListItem mItem, String mShopName)
        //{
        //    if (!mItem.HasUniqueRoleAssignments)
        //    {
        //        mItem.BreakRoleInheritance(true);
        //    }
        //    //---------------------------------------
        //    SPRoleAssignmentCollection ImageItemRoles = mItem.RoleAssignments;
        //    while (ImageItemRoles.Count > 0)
        //        ImageItemRoles.Remove(0);
        //    //---------------------------------------
        //    using (SPSite Site = new SPSite(sUrl))
        //    {
        //        using (SPWeb mWeb = Site.OpenWeb())
        //        {
        //            SPRoleDefinition roleDef = mWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
        //            SPGroup mGroup;
        //            if (SPSecurityHelper.GetWeGroup(Site, mShopName) != null)
        //            {
        //                mGroup = SPSecurityHelper.GetWeGroup(mWeb, mShopName);
        //                SPRoleAssignment RoleAssignment = new SPRoleAssignment(mGroup);
        //                RoleAssignment.RoleDefinitionBindings.Add(roleDef);
        //                mItem.RoleAssignments.Add(RoleAssignment);
        //            }

        //            SPList list = mWeb.Lists["PermDocRight"];
        //            if (list != null)
        //            {
        //                foreach (SPListItem Item in list.Items)
        //                {
        //                    if (SPSecurityHelper.GetNameGroupByString(Item["Group"].ToString()) != null)
        //                    {
        //                        if (SPSecurityHelper.GetWeGroup(mWeb, SPSecurityHelper.GetNameGroupByString(Item["Group"].ToString())) != null)
        //                        {
        //                            mGroup =
        //                                SPSecurityHelper.GetWeGroup(
        //                                        mWeb
        //                                    , SPSecurityHelper.GetNameGroupByString(Item["Group"].ToString()));
        //                            SPRoleDefinition rolePerm = null;
        //                            //--
        //                            string type = Item["Perm"].ToString();
        //                            if (type == "Administrator")
        //                                rolePerm =
        //                                    mWeb.RoleDefinitions.GetByType(SPRoleType.Administrator);
        //                            if (type == "Contributor")
        //                                rolePerm =
        //                                    mWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
        //                            if (type == "Reader")
        //                                rolePerm =
        //                                    mWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
        //                            //--
        //                            if (rolePerm != null)
        //                            {
        //                                SPRoleAssignment RoleAssignment = new SPRoleAssignment(mGroup);
        //                                RoleAssignment.RoleDefinitionBindings.Add(rolePerm);
        //                                mItem.RoleAssignments.Add(RoleAssignment);
        //                            }
        //                        } // if (GetWeGroup(GetNameGroupByString(Item["Group"].ToString())) != null)
        //                    } // if (GetNameGroupByString(Item["Group"].ToString()) != null)
        //                } // foreach (SPListItem Item in list.Items)
        //            } // if (list != null)
        //        } // using (SPWeb mWeb = Site.OpenWeb())
        //    } // using (SPSite Site = new SPSite(sUrl))
        //}
        #endregion Rigth

    }

}
